<?php

namespace app\admin\controller\information;

use app\common\controller\Backend;
use think\Db;
use think\Request;
use think\Log;
use think\File;
use think\exception\PDOException;
use think\Exception;
/**
 * 物料档案管理
 *
 * @icon fa fa-circle-o
 */
class Inventory extends Backend
{
    /**
     * Inventory模型对象
     * @var \app\admin\model\information\Inventory
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\information\Inventory;
        $this->view->assign("sourceList", $this->model->getSourceList());
        
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->relationSearch = true;
        //快速搜索，针对有关联模型的，模型名.字段
        $this->searchFields = 'inventory.name,inventory.number,unit,store_unit,inventory.name_specification';
        
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        
        $op = $this->request->get("op", '', 'trim');
        $op = (array)json_decode($op, true);
        $filter = $this->request->get("filter", '');
        $where2 = [];
        if($filter){
            $filter=urldecode($filter);
            $filter=json_decode($filter,TRUE);
            if(isset($filter['image_url'])){
                //0无，1有
                if($filter['image_url']){
                    $where2['inventory.image_url'] = ['neq','not null']; //不为空
                }else{
                    $where2['inventory.image_url'] = null;
                }
                unset($filter['image_url'],$op['image_url']);
            }
            $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
        }
        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->with(['warehouse','shelves','invshlatest'])
        ->where($where)
        ->where($where2)
        ->order($sort, $order)
        ->paginate($limit);
        
        //生成缩略图
        /* if($list){
            foreach ($list as &$item){
                if($item->image_url){
                    $arr = explode(',', $item->image_url);
                    foreach ($arr as $path){
                        if(!file_exists(cdnurl($path.'.s.png',true))){
                            //缩略图
                            $imagePath = cdnurl($path,true);
                            $img = \think\Image::open($imagePath);
                            $img->thumb(400,400);
                            $small_img = ROOT_PATH . 'public'.$path.'.s.png';
                            $img->save($small_img);//保存 
                        }
                    }
                    $item->is_thumb = true;
                }
            }
        } */
        
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    /**
     * 复制并新增
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function copy()
    {
        $number = $this->request->post('number','');
        
        $row = db('inventory')->where(['number'=>$number])->find();
        //$row = $this->model->get(['number'=>$number]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        
        $result = false;
        Db::startTrans();
        try {
            $row['name'] = $row['name'].'【良品】';//良品
            $row['number'] = 'LP'.$row['number'];//良品
            $row['source'] = 1;
            unset($row['id'],$row['createtime'],$row['updatetime'],$row['deletetime']);
            $result = $this->model->allowField(true)->save($row);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            if(strpos($e->getMessage(), '1062')){
                $this->error('已存在该编码，请核实');
            }else{
                $this->error($e->getMessage());
            }
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        if (false === $this->request->isPost()) {
            $row = $this->model->getInvObj($row->getAttr('number'),true);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            if(strpos($e->getMessage(), '1062')){
                $this->error('已存在该编码，请核实');
            }else{
                $this->error($e->getMessage());
            }
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function getData()
    {
        Db::startTrans();
        try {
            $this->model->getInventoryData();
            
            //更新组合字段，方便搜索
            //db('inventory')->execute("UPDATE fa_inventory set name_specification=CONCAT(name,specification)");
            
            Log::info('手动同步物料完成');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            Log::error('手动同步物料失败'.$e->getMessage());
            $this->error($e->getMessage());
        }
		$this->success("同步完成");
    }

    public function print()
    {
        $params =$this->request->param();
        $ids = $params['inventory_id'];
        $domain = request()->domain();
        $ids_arr = explode(',',$ids);
        $list = [];

        if(isset($params['type'])){
            $list = $this->model
            ->alias('i')
            ->join('shelves s','i.shelves_id = s.id','left')
            ->field('i.*,s.name as shelvesName,s.column_number,s.row_number,s.layers_number,s.type')
            ->where(function($query)use($params){
                if(isset($params['type']))
                    $query->where(['i.warehouse_code'=>['in',$params['inventory_id']],'i.deletetime'=>null]);
                else
                    $query->where(['i.id'=>['in',$params['inventory_id']],'i.deletetime'=>null]);
            })
            ->select();
        }else{
            foreach($ids_arr as $id){
                $list[] = $this->model
                ->alias('i')
                ->join('shelves s','i.shelves_id = s.id','left')
                ->field('i.*,s.name as shelvesName,s.column_number,s.row_number,s.layers_number,s.type')
                ->where(function($query)use($id){
                    $query->where(['i.id'=>$id,'i.deletetime'=>null]);
                })
                ->find();
            }
        }
       
        if(empty($list)) return '暂无信息';
        //二维码设置宽度,padding
        foreach ($list as $k=>&$v){
            $v['cBatch'] ='';
            if(isset($params['cBatch'])){
                $cBatch_arr = explode(',',$params['cBatch']);
                if(isset($cBatch_arr[$k])){
                    $v['cBatch'] = $cBatch_arr[$k];
                }
            }
        }
        unset($v);
        
        $this->assign('list',$list);
        return $this->view->fetch();
    }

    public function choose(){
        return $this->index();
    }
    

   public function choosebyclass(){

       $this->request->filter(['strip_tags', 'trim']);
       if (false === $this->request->isAjax()) {
           return $this->view->fetch();
       }
       //如果发送的来源是 Selectpage，则转发到 Selectpage
       if ($this->request->request('keyField')) {
           return $this->selectpage();
       }
       $this->searchFields = 'number,name';
       [$where, $sort, $order, $offset, $limit] = $this->buildparams(null,null,1);
       $list = $this->model
           ->where($where)
           ->where("number not like '0810%'")
           ->order($sort, $order)
           ->paginate($limit);
       $result = ['total' => $list->total(), 'rows' => $list->items()];
       return json($result);
   }

}
